<template>
  <div v-loading="state.loading" class="container" ref="nodeRef">
 
      <div class="handle">
        <el-input
          v-model="searchValue" 
          :placeholder="$t('goods_document.annex_name')"
          :suffix-icon="Search"
          clearable
          @change="init(state.certifyObj)"
      />
      <el-button link @click="init(state.certifyObj,'init')">{{ $t("merak.refresh") }}</el-button>
      </div>
      <el-table class="merak-table-container" table-layout="auto" :data="state.data" :max-height="300" scrollbar-always-on>
        <el-table-column prop="name" :label="$t('goods_document.annex_name')" />
        <el-table-column :label="$t('goods_document.annex_type')"  width="200">
          <template #default="{ row }">{{ (row.type ?? "").toUpperCase() }}</template>
        </el-table-column>
        <el-table-column prop="created_username" :label="$t('goods_document.create_poper')"  width="230"/>
        <el-table-column prop="created_at" :label="$t('goods_document.create_time')" width="230"/>
        <el-table-column :label="$t('merak.action')" width="150">
          <template #default="{ row }">
            <!-- <a :href="row.file_url" target="__blank" download> -->
            <el-button type="primary" :loading="loadingKey.includes(row.gc_file_id)" link @click="download(row)">
              {{ $t("merak.download") }}
            </el-button>
            <!-- </a> -->
          </template>
        </el-table-column>
        <template #empty>
          <div v-if="state.loadedData" style="padding: 100px 40px 0">
            <img :src="EmptyPng" style="object-fit: cover; height: 130px" />
          </div>
          <div v-else></div>
        </template>
      </el-table>
    
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from "vue";

import { useRoute } from "vue-router";

import { ElMessage, ElInput, ElButton, ElTable, ElTableColumn } from "element-plus";
import { Search } from "@element-plus/icons-vue";

import UploadFileMerak from "@/components/uploadFileMerak/index.vue";

import { ResultEnum } from "@/enums/httpEnum";
 
import { getCertifyApi, getProductInfoApi } from "@/api/modules/goodsArchive/list/detail";
 
import { confirmWarningMsg } from "@/utils/messageUtils";

import EmptyPng from "@/assets/images/empty.png";
import { onUnmounted } from "vue";

const props = defineProps<{
  queueId?: string;
  productId?: string|number;
}>();

const emit = defineEmits<{
  change: [];
}>();

const currentInstance = getCurrentInstance();

const route = useRoute();

const nodeRef = ref<HTMLDivElement>();

const observeRef = ref<ResizeObserver>();

const uploadRef = ref<InstanceType<typeof UploadFileMerak>>();

const searchValue = ref<string>();

const loadingKey = ref<Array<string | number>>([]);

const recordNum = ref(0);

const state = reactive<{
  certifyObj:object,
  loading: boolean;
  loadedData: boolean;
  data: Array<Record<string, any>>;
  fileList: Array<Record<string, any>>;
}>({
  certifyObj:{},
  loading: false,
  loadedData: false,
  data: [],
  fileList: []
});

const init = async (certifyObj,type) => {
    state.certifyObj=certifyObj;
   state.loading = !!props.queueId ? false : true;
  await getProductInfoApi({ product_id: props.productId, goods_certify_id: certifyObj?.goods_certify_id, type: "file" },props.queueId).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      if(type=="init"){
        searchValue.value="";
      }
      const filterValue = (searchValue.value ?? "").toLowerCase();
      recordNum.value = data.length;
      state.loadedData = true;
      state.data = data.filter(item => (item.name ?? "").toLowerCase().includes(filterValue));
    }
  });
  state.loading = false;
};

const download = async (row: Record<string, any>) => {
  loadingKey.value.push(row.gc_file_id);
  const link = document.createElement("a");
  link.href = row.file_url;
  link.download = row.name ?? Date.now().toString();
  link.target = "_blank";
  link.click();
  // await downloadFile(row.file_url, row.name).then(status => {
  //   if (!status) {
  //     ElMessage.error(`${row.name} ${currentInstance?.proxy?.$t("merak.download_error")}`);
  //   }
  // });
  const index = loadingKey.value.findIndex(key => key === row.gc_file_id);
  loadingKey.value.splice(index, 1);
};

onMounted(() => {
  // init({},"init");
  observeRef.value = new ResizeObserver(() => {
    emit("change");
  });
  if (nodeRef.value) {
    observeRef.value.observe(nodeRef.value);
  }
});

onUnmounted(() => {
  if (!!observeRef.value && !!nodeRef.value) {
    observeRef.value.unobserve(nodeRef.value);
  }
});

defineExpose({
  reload: () => init({},"init"), 
  init,
  recordNum
});
</script>

<style scoped lang="scss">
.handle {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--merak-space);
  .el-input {
    width: 200px;
  }
  .el-button {
    margin: 0;
    padding: 0;
    min-width: auto;
    border: none;
    &:hover,
    &:focus {
      color: var(--el-color-primary) !important;
    }
  }
}
</style>
